<?php
/**
 * 表单验证
 */

declare (strict_types=1);

namespace app\admin\middleware;

use app\common\service\admin\AuthService;
use Closure;
use think\exception\HttpResponseException;
use think\Request;
use think\Response;

class FormTokenCheck
{

    use \app\common\traits\JumpTrait;

    // 定义排除列表
    // 可以添加其他需要排除的控制器方法
    protected $exclude = [
        'upload/index',
        'upload/ueditor_config',
        'upload_file/file_list',
        'upload_file/group_list',
        'login/logout'
    ];

    /**
     * 表单令牌检测
     * @access public
     *
     * @param Request $request
     * @param Closure $next
     * @param string  $token 表单令牌Token名称
     *
     * @return Response
     */
    public function handle(Request $request, Closure $next, string $token = null)
    {
        // 跳过参数中包含：no_need__token__==1的请求
        $no_need__tooken__ = (int)$request->post('no_need__token__') ?? 0;
        if ($no_need__tooken__ === 1) {
            return $next($request);
        }

        // 获取当前请求的控制器和方法
        //var_dump($request->post());
        $controller   = request()->controller();
        $action       = request()->action();
        $currentRoute = uncamelize($controller.'/'.$action);

        // 检查是否在排除列表中
        if (in_array($currentRoute, $this->exclude)) {
            return $next($request);
        }

        $check = $request->checkToken($token ?: '__token__');

        if (false === $check) {
            $result = [
                'code' => -1000,
                'msg'  => lang('invalid token'),
                'data' => ['__token__' => $request->buildToken()],
                'url'  => '',
                'wait' => 0,
            ];

            throw new HttpResponseException(json($result));
        }

        return $next($request);
    }
}
